$(function(){
	
	var commonUrl = '/course-work-management/teacher';
	
	// Tooltip
	$('[data-tooltip="true"]').tooltip();
	
	// Load course and its teacher works for the first time
	initCoursesAndStudents();
	
	// Reset form after hidding the modal
	$('.modal').on('hidden.bs.modal', function() {
        if($(this).find('form')) {
            $(this).find('form')[0].reset();
        }
        if($(this).find('.alert')) {
        	$(this).find('.alert').alert('close');
        }
    });
	
	// Show a modal and add a new course
	$('#addCourseModal button:last').on('click', function(){
		if ($('#addCourseModal input').val().length == 0) {
			$('#addCourseModal .modal-body').prepend(createAlert('danger', 'Error', '课程名称不为空！'));
		} else {
			var param = {
					courseName : $('#addCourseModal input').val(),
					courseNo : $('#addCourseModal option:selected').text()
			};
			$.post(commonUrl + '/course/action/add', param, function(result){
				if(result.succeeded){
					$('#addCourseModal').modal('hide');
					initCoursesAndStudents();
				} else {
					$('#addCourseModal .modal-body').prepend(createAlert('danger', 'Error', result.message));
				}
			});
		}
	});
	
	// Delete course and alert message
	$('#deleteCourseModal button:last').on('click', function(){
		$.ajax({
			url: commonUrl + '/course/id/' + $('#courses select option:selected').val(),
			type: 'DELETE',
		}).done(function(result){
			$('#deleteCourseModal').modal('hide');
			if(result.succeeded){
				initCoursesAndStudents();
			} else {
				$('.container:eq(1)').prepend(createAlert('danger', 'Error', result.message));
			}
		});
	});
	
	// Change course option and get teacher works of this course
	$('#courses select').on('change', function(){
		// Reset teacher work and student works panel
		resetWorkPanel();
		loadStudentsData($('#courses select option:selected').val())
	});

	// Show a modal and add a new teacher work
    $('#addStudentModal .modal-footer button:last').on('click', function() {
    	if ($('#addStudentModal input').val().length == 0) {
    		$('#addStudentModal .modal-body').prepend(createAlert('danger', 'Error', '学号不为空！'));
    	} else {
    		var param = {
    				no: $('#addStudentModal input').val(),
    				courseId: $('#courses select option:selected').val()
    		}
    		$.post(commonUrl + '/student/action/add', param, function(result) {
    			if(result.succeeded) {
    				$('#addStudentModal').modal('hide');
    				loadStudentsData($('#courses select option:selected').val());
    			} else {
    				$('#addStudentModal .modal-body').prepend(createAlert('danger', 'Error', result.message));
    			}
    		});
    	}
    }); 
    
    // Show a modal and delete teacher work
    $('#deleteStudentModal .modal-footer button:last').on('click', function() {
    	$.ajax({
    		url: commonUrl + '/course/id/' + $('#courses select option:selected').val() + '/student/id/' + $('#workPanelHeading').data('id'),
    		type: 'DELETE'
    	}).done(function(result) {
    		$('#deleteStudentModal').modal('hide');
    		if(result.succeeded) {
    			resetWorkPanel();
    			loadStudentsData($('#courses select option:selected').val());
    		} else {
    			$('.container:eq(1)').prepend(createAlert('danger', 'Error', result.message));
    		}
    	});
    });
	
	// Refresh course data
	function loadCoursesData() {
		return $.get(commonUrl + '/courses', function(data){
				   $('#courses select').empty();
				   $.each(data, function(index){
					   $('#courses select').append('<option value="' + data[index].id + '">' + data[index].courseName + '_' + data[index].courseNo +'</option>');
				   });
			   });
	}
	
	// Refresh students data
	function loadStudentsData(courseId) {
		var studentsDiv = $("#students .list-group div");
		$.get(commonUrl + '/course/id/' + courseId + '/students', function(data){
			studentsDiv.empty();
			$.each(data, function(index){
				studentsDiv.append('<a href="" class="list-group-item" style="margin-bottom: 5px;" data-id="' + data[index].id + '">' + data[index].no + '-' + data[index].name + '</a>');
			});
		}).done(function(){
			if(studentsDiv.find('a')) {
				studentsDiv.find('a').on('click', function(e){
				   	e.preventDefault();
				   	loadCurrentStudentWorksData($(e.target).data('id'), getStudentNameFromItemText($(e.target).text()), $('#courses select option:selected').val());
				});
			}
		});
	}
	
	// Refresh current course's student works
	function loadCurrentStudentWorksData(studentId, studentName, courseId){
    	// Get student works
    	$.get(commonUrl + '/course/id/' + courseId +'/student/id/' + studentId + '/student-works', function(data){
    		$('#workPanelHeading li:eq(0)').text($('#courses select option:selected').text());
    		$('#workPanelHeading li:eq(1)').text(studentName);
    		$('#workPanelHeading').data('id', studentId);
    		$('#workPanelHeading button').show();
    		$('#studentWorks table tbody').empty();
    		$.each(data, function(index){
    			if(data[index].submitted) {
    				$('#studentWorks table tbody').append(
	    				'<tr class="success" style="margin-top:5px;">' +
	    					'<td>' + data[index].student.no + '</td>' +
	    					'<td>' + data[index].student.name + '</td>' + 
	    					'<td>' + getFormattedTime(data[index].submitDate) + '</td>' +
	    					'<td>' +
	    						'<a href="' + commonUrl + '/student-work/id/' + data[index].id + '/attachment">' + getFileName(data[index].filePath) + '</a>' +
	    					'</td>' + 
	    					'<td>' + data[index].score + '</td>' +
	    				'</tr>'
    	    		);
    			} else {
    				$('#studentWorks table tbody').append(
	    				'<tr class="danger" style="margin-top:5px;">' +
	    					'<td>' + data[index].student.no + '</td>' +
	    					'<td>' + data[index].student.name + '</td>' + 
	    					'<td></td>' +
	    					'<td></td>' + 
	    					'<td></td>' +
	    				'</tr>'
        	    	);
    			}
    		});
    	});
	}
	
	function initCoursesAndStudents() {
		loadCoursesData().done(function(){
			if($('#courses select').find('option')) {
				loadStudentsData($('#courses select:first-child').val());
			}
		});
	}
	
	// Reset teacher work and student works panel
	function resetWorkPanel() {
		$('#workPanelHeading li:eq(0)').text('');
		$('#workPanelHeading li:eq(1)').text('');
		$('#workPanelHeading').data('id', '');
		$('#workPanelHeading button').hide();
		$('#studentWorks table tbody').empty();
	}
	
	// Format time
	function getFormattedTime(time) {
		var date = new Date();
		date.setTime(time);
		return date.format('yyyy-mm-dd  HH:mm:ss');
	}
	
	// get file name from file path
	function getFileName(filePath) {
		return String(filePath).substring(filePath.lastIndexOf("/") + 1);
	}
	
	// getStudentName
	function getStudentNameFromItemText(text) {
		return String(text).substring(text.lastIndexOf("-") + 1);
	}
	
	// Make alert
	function createAlert(status, tip, message) {
		return '<div class="alert alert-' + status + '"><a href="#" class="close" data-dismiss="alert">&times;</a><strong>' + tip + '! </strong>' + message + '</div>'
	}
	
});